package com.idata.model.Builder;

import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.idata.model.dto.KGProxySearchResultDTO;
import com.idata.model.dto.TagDTO;
import com.idata.model.proxyDO.KGCitizenDO;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

public class KGProxySearchBuilder {

    private static final List<String> noTagList = ListUtil.toList("性别", "年龄", "籍贯");

    public static List<KGProxySearchResultDTO> transferFromJsonObject(JSONObject jsonObject) {
        List<KGProxySearchResultDTO> result = new ArrayList<>();
        JSONArray data = jsonObject.getJSONArray("data");
        for (int i = 0; i < data.size(); i++) {
            JSONObject disputeJsonObjForOnePerson = data.getJSONObject(i);
            JSONObject tag = disputeJsonObjForOnePerson.getJSONObject("tag");
            List<TagDTO> tags = getTagList(tag);
            KGCitizenDO kgCitizenDO = disputeJsonObjForOnePerson.toJavaObject(KGCitizenDO.class);
            result.add(new KGProxySearchResultDTO(kgCitizenDO, tags));
        }
        return result;
    }

    private static List<TagDTO> getTagList(JSONObject tag) {
        List<TagDTO> tagDTOS = new ArrayList<>();
        for (Entry<String, Object> entry : tag.entrySet()) {
            String jsonKey = entry.getKey();
            Object jsonValue = entry.getValue();
            if ((!jsonKey.startsWith("标签_")) || (! jsonKey.endsWith("META_NAME"))) {
                continue;
            }
            String pureTagKey = jsonKey.replaceAll("标签_", "").replaceAll(".META_NAME", "");
            if (noTagList.contains(pureTagKey)) {
                continue;
            }
            if (!(jsonValue instanceof String)) {
                continue;
            }
            try {
                // 如果转成数字成功了，那就continue过滤掉，如果发生了异常，表明是中文，则继续剩下的操作
                Integer num = Integer.valueOf((String) jsonValue);
                continue;
            } catch (NumberFormatException e) {

            }
            String tagValue = ((String) jsonValue).replace("标签_", "");
            tagDTOS.add(new TagDTO(pureTagKey, tagValue));
        }
        return tagDTOS;
    }
}
